package com.ge.med.cchelper.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class TextHelper {
	public final static String CHECKOUT_FILE = "checkout.properties";

	public static boolean writeText(String savepath, String message)
			throws Exception {
		File saveFile = new File(savepath);
		if (!saveFile.exists()) {
			saveFile.createNewFile();
		}
		BufferedWriter bw = new BufferedWriter(new FileWriter(saveFile, true));
		bw.append(message+"\r\n");
		bw.close();
		return true;
	}
	
	public static void clear(String savepath) throws Exception{
		File saveFile = new File(savepath);
		if (saveFile.exists()) {
			FileWriter fw =  new FileWriter(saveFile);
			fw.write("");
			fw.close();
		}
	}

	public static boolean isExists(String savepath, String message)
			throws Exception {
		File saveFile = new File(savepath);
		if (!saveFile.exists()) {
			return false;
		}

		return isExists(saveFile,message);
	}
	
	public static boolean isExistsLikePath(String savepath, String message) throws Exception{
		File saveFile = new File(savepath);
		if (!saveFile.exists()) {
			return false;
		}
		BufferedReader br = new BufferedReader(new FileReader(saveFile));
		String tempStr = "";
		while ((tempStr = br.readLine()) != null) {
			if (tempStr.trim().startsWith(message)) {
				return true;
			}
		}
		br.close();
		
		return false;
	}
	
	public static boolean isExists(File saveFile, String message)
			throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(saveFile));
		String tempStr = "";
		while ((tempStr = br.readLine()) != null) {
			if (tempStr.trim().equals(message)) {
				return true;
			}
		}
		br.close();
		return false;
	}

	public static void remove(String savepath, String message) throws Exception {
		File saveFile = new File(savepath);
		if (!saveFile.exists()) {
			return;
		}
		List<String> texts = new ArrayList<String>();
		BufferedReader br = new BufferedReader(new FileReader(saveFile));
		String tempStr = "";
		while ((tempStr = br.readLine()) != null) {
			if (!tempStr.trim().equals(message.trim())) {
				texts.add(tempStr);
			}
		}
		br.close();
		BufferedWriter bw = new BufferedWriter(new FileWriter(saveFile));
		bw.write("");
		for (String s : texts) {
			bw.append(s+"\r\n");
		}
		bw.close();
	}

}
